package zhongbo.java.air.listener;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import zhongbo.java.air.config.RedisListenerConfig; // 添加导入
import zhongbo.java.air.model.AirFlightPath;
import zhongbo.java.air.service.AirFlightPathService;

@Component
@Slf4j
public class RedisSubscribeLogChannelListener implements MessageListener {

    @Autowired
    private AirFlightPathService<AirFlightPath> airFlightPathService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        log.info("从信道接收消息 '{}': {}", channel, body);

        // 打印日志到控制台
        System.out.println("通道日志 '" + channel + "': " + body);

        // 忽略包含action字段的消息体
        if (body.contains("\"action\"")) {
            log.info("忽略包含action字段的消息体: {}", body);
            return;
        }

        // 验证timestamp格式
        try {
            objectMapper.readValue(body, AirFlightPath.class);
        } catch (JsonMappingException e) {
            if (e.getCause() instanceof NumberFormatException) {
                log.error("时间戳格式错误: {}", body, e);
                return;
            }
            log.error("解析消息体失败: {}", body, e);
            return;
        } catch (Exception e) {
            log.error("解析消息体失败: {}", body, e);
            return;
        }

        try {
            // 解析消息体为AirFlightPath对象
            AirFlightPath airFlightPath = objectMapper.readValue(body, AirFlightPath.class);
            // 保存航迹数据
            airFlightPathService.add(airFlightPath);
            System.out.println("保存航迹数据：" + airFlightPath);
            // 广播航迹信息到INST_FLIGHT_PATH频道
            String flightPathJson = JSONUtil.toJsonStr(airFlightPath);

            System.out.println("广播航迹信息到INST_FLIGHT_PATH频道：" + flightPathJson);
            // 修改: 使用RedisListenerConfig中的INST_FLIGHT_PATH常量
            redisTemplate.convertAndSend(RedisListenerConfig.INST_FLIGHT_PATH, flightPathJson);
        } catch (RedisSystemException e) {
            log.error("Redis系统异常: {}", body, e);
        } catch (Exception e) {
            log.error("解析消息体失败: {}", body, e);
        }
    }
}